package com.jackxuechen.liujie.libgdxdemo

import com.badlogic.gdx.Application
import com.badlogic.gdx.ApplicationListener
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Preferences
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.SpriteBatch


/**
 * Created by liujie on 2017/7/29.
 */

class MainGame : ApplicationListener {
    // 纹理画布
    private var batch: SpriteBatch? = null
    // 纹理
    private var texture: Texture? = null

    override fun create() {
        Gdx.app.logLevel = Application.LOG_ERROR

        Gdx.app.debug("debug", "create")
        Gdx.app.log("log", "create")
        Gdx.app.error("error", "create")

        // 创建纹理画布
        batch = SpriteBatch()

        /*
         * 使用 assets 文件夹中的图片 badlogic.jpg 创建纹理,
         * 文件路径相对于 assets 文件夹根目录, 如果图片放在子目录, 则路径为 "xxx/badlogic.jpg"
         */
        texture = Texture("a.jpg")
        fileDemo()
        preferencesDemo()

    }

    private fun fileDemo() {
        val isExtAvailable = Gdx.files.isExternalStorageAvailable
        val isLocAvailable = Gdx.files.isLocalStorageAvailable
        println("isExtAvailable:$isExtAvailable,isLocAvailable:$isLocAvailable")
        val extRoot = Gdx.files.externalStoragePath
        val locRoot = Gdx.files.localStoragePath
        println("extRoot:$extRoot,locRoot:$locRoot")
        val intHandle = Gdx.files.internal("config.txt")
        println("intHandle:${intHandle.exists()},${intHandle.readString()}")
        val locHandle = Gdx.files.local("localFile.txt")
        if (!locHandle.exists()) {
            locHandle.writeString("new file", true)
        }
        println("locHandle:${locHandle.exists()},${locHandle.readString()}")
        val extHandle = Gdx.files.external("extFile.txt")
        if (!extHandle.exists()) {
            extHandle.writeString("new file", true)
        }
        println("extHandle:${extHandle.exists()},${extHandle.readString()}")

    }

    private fun preferencesDemo() {
        val p: Preferences = Gdx.app.getPreferences("config")
        p.putString("name", "liujie")
        p.putBoolean("is", true)
        p.putFloat("f", 1.0F)
        p.flush()
        val mutableMap = p.get()
        mutableMap.entries.forEach { en -> println("key:${en.key},value:${en.value}") }


    }

    override fun resize(i: Int, i1: Int) {

    }

    override fun render() {
        // 设置清屏颜色为红色
        Gdx.gl.glClearColor(0f, 0f, 0f, 100f)
        // 清屏
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
        batch?.begin()              // 绘制开始
        batch?.draw(texture!!, -250f, 100f)  // 在屏幕左下角绘制纹理
        batch?.end()                // 绘制结束
    }

    override fun pause() {

    }

    override fun resume() {

    }

    override fun dispose() {
        batch?.dispose()
        texture?.dispose()
    }
}
